<script setup lang="ts">
import  WMSCapabilities from 'ol/format/WMSCapabilities';
import WMSGetFeatureInfo from 'ol/format/W';
import { TileWMS } from 'ol/source';
import { onMounted } from 'vue';
import { Map, View } from 'ol';
import {Tile as TileLayer } from 'ol/layer';

let url = 'https://iserver.supermap.io/iserver/services/map-world/wms111/World';
let wfsUrl = 'https://iserver.supermap.io/iserver/services/data-world/wfs100/utf-8';
onMounted(async () => {
  let view = new View({
    center: [0, 0],
    projection: "EPSG:4326", // 坐标系，有EPSG:4326和EPSG:3857
    zoom: 12 // 地图缩放级别（打开页面时
  });
  const wmsLayer = await loadWmsLayer();
  let map = new Map({
    target: 'map',
    layers: [wmsLayer],
    view: view,
  });
});

async function loadWmsLayer() : Promise<TileLayer> {
  try {
    const parse = new WMSCapabilities();
    const response = await fetch(url + '?request=GetCapabilities&service=WMS');
    const text = await response.text();
    const result = parse.read(text);
    const wmsLayer = createWmsLayer(result);
    return Promise.resolve(wmsLayer);
  }catch (error) {
    console.error(error);
    return Promise.reject(error);
  }
}

async function loadWfsLayer() : Promise<TileLayer> {
  try {
    const parse = new WMSGetFeatureInfo();
    const response = await fetch(url + '?request=GetCapabilities&service=WFS');
    const text = await response.text();
    const result = parse.read(text);
    const wmsLayer = createWmsLayer(result);
    return Promise.resolve(wmsLayer);
  }catch (error) {
    console.error(error);
    return Promise.reject(error);
  }
}
function createWmsLayer(capabilities: { Capability: { Layer: { Layer: any[]; }; }; version: any; }) { 
  const layerInfo = capabilities.Capability.Layer.Layer[0];
  const wmsSource = new TileWMS({
    url: url,
    params: {
      'LAYERS': layerInfo.Name,
      'TILED': true,
      'VERSION': capabilities.version
    }
  })
  return new TileLayer({
        source: wmsSource,
        opacity: 0.7,
  });
}

</script>

<template>
  <div id="map" style="width: 1000px; height: 500px;">
  </div>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
